package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.auth.constants.JwtConstants.COOKIE_NAME;
import static com.leyou.auth.constants.JwtConstants.DOMAIN;

/**
 * @author 虎哥
 */
@Slf4j
@Service
public class  UserAuthServiceImpl implements UserAuthService {

    private final UserClient userClient;
    private final JwtUtils jwtUtils;

    public UserAuthServiceImpl(UserClient userClient, JwtUtils jwtUtils) {
        this.userClient = userClient;
        this.jwtUtils = jwtUtils;
    }

    @Override
    public void login(String username, String password, HttpServletResponse response) {
        try {
            // 1.到ly-user查询用户
            UserDTO user = userClient.queryUserByUsernameAndPassword(username, password);

            // 2.如果用户正确，生成JWT
            // 2.1.构建UserDetails
            UserDetails details = UserDetails.of(user.getId(), user.getUsername());
            // 2.2.生成JWT
            String jwt = jwtUtils.createJwt(details);

            // 3.把jwt写入cookie
            writeCookie(response, jwt);

        } catch (FeignException e) {
            // 如果用户信息是错误的，返回错误信息, e.status()是feign调用的状态码，e.contentUTF8()是异常消息
            throw new LyException(e.status(), e.contentUTF8());
        }
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        // 获取cookie
        String jwt = CookieUtils.getCookieValue(request, COOKIE_NAME);
        if(jwt == null){
            // 用户未登录，无需退出
            return;
        }
        try {
            // 获取用户信息
            Payload payload = jwtUtils.parseJwt(jwt);
            Long userId = payload.getUserDetail().getId();
            //根据用户信息，删除redis中的jti
            jwtUtils.deleteJwt(userId);
        } catch (Exception e) {
            log.error("用户登录无效，无需退出");
        }
        //删除cookie
        CookieUtils.deleteCookie(COOKIE_NAME, DOMAIN, response);
    }

    private void writeCookie(HttpServletResponse response, String jwt) {
        Cookie cookie = new Cookie(COOKIE_NAME, jwt);
        cookie.setDomain(JwtConstants.DOMAIN);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }
}
